<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { dataControlApi } from '@/api'

const router = useRouter()

// 响应式数据
const statistics = reactive({
  totalRules: 0,
  publishedRules: 0,
  totalGroups: 0,
  todayExecutions: 0
})

const recentExecutions = ref([])
const autoControlLoading = ref(false)

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 加载规则统计
    const rulesResponse = await dataControlApi.getRuleList({ pageNo: 1, pageSize: 1 })
    statistics.totalRules = rulesResponse.total || 0
    
    const publishedResponse = await dataControlApi.getRuleList({ 
      pageNo: 1, 
      pageSize: 1, 
      publishStatus: 'PUBLISHED' 
    })
    statistics.publishedRules = publishedResponse.total || 0
    
    // 加载分组统计
    const groups = await dataControlApi.getGroupTree()
    statistics.totalGroups = countGroups(groups)
    
    // 模拟今日执行次数
    statistics.todayExecutions = Math.floor(Math.random() * 20) + 5
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 计算分组总数
const countGroups = (groups) => {
  let count = groups.length
  groups.forEach(group => {
    if (group.children && group.children.length > 0) {
      count += group.children.length
    }
  })
  return count
}

// 加载最近执行记录
const loadRecentExecutions = async () => {
  try {
    const logs = await dataControlApi.getExecutionHistory({ pageNo: 1, pageSize: 5 })
    recentExecutions.value = logs.slice(0, 3) // 只显示最近3条
  } catch (error) {
    console.error('加载执行记录失败:', error)
  }
}

// 查看执行详情
const viewExecutionDetail = (log) => {
  router.push(`/datacontrol/execution?executionId=${log.executionId}`)
}

// 快速自动检控
const quickAutoControl = async () => {
  try {
    await showConfirmDialog({
      title: '确认执行',
      message: '确定要执行自动检控吗？这将执行所有已发布的规则。'
    })
    
    autoControlLoading.value = true
    const executionId = await dataControlApi.executeAutoControl()
    showToast(`自动检控已启动，执行ID: ${executionId}`)
    
    // 刷新执行记录
    setTimeout(() => {
      loadRecentExecutions()
      loadStatistics()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('启动失败: ' + error.message)
    }
  } finally {
    autoControlLoading.value = false
  }
}

// 获取执行状态类型
const getExecutionStatusType = (status) => {
  const typeMap = {
    'RUNNING': 'primary',
    'SUCCESS': 'success',
    'FAILED': 'danger'
  }
  return typeMap[status] || 'default'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadStatistics()
  loadRecentExecutions()
})
</script>

<template>
  <div class="page-container">
    <van-nav-bar 
      title="数据检控" 
      left-arrow 
      @click-left="router.back()"
    />

    <div class="content">
      <!-- 功能概览 -->
      <van-cell-group inset class="overview-card">
        <van-cell>
          <template #title>
            <div class="overview-info">
              <div class="overview-title">🔍 数据检控管理系统</div>
              <div class="overview-desc">对进入外部数据审核库的数据进行全面的质量检控</div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 快速统计 -->
      <van-cell-group inset title="系统统计">
        <van-cell title="检控规则总数" :value="statistics.totalRules" />
        <van-cell title="已发布规则" :value="statistics.publishedRules" />
        <van-cell title="规则分组数" :value="statistics.totalGroups" />
        <van-cell title="今日执行次数" :value="statistics.todayExecutions" />
      </van-cell-group>

      <!-- 主要功能 -->
      <van-cell-group inset title="功能管理">
        <van-cell 
          title="检控规则管理" 
          label="配置和管理数据检控规则"
          is-link 
          @click="navigateTo('/datacontrol/rules')"
          icon="shield-o"
        />
        <van-cell 
          title="规则分组管理" 
          label="管理检控规则的分组结构"
          is-link 
          @click="navigateTo('/datacontrol/groups')"
          icon="cluster-o"
        />
      </van-cell-group>

      <!-- 检控执行 -->
      <van-cell-group inset title="检控执行" style="margin-top: 12px;">
        <van-cell 
          title="执行检控" 
          label="执行数据检控和查看结果"
          is-link 
          @click="navigateTo('/datacontrol/execution')"
          icon="play-circle-o"
        />
      </van-cell-group>

      <!-- 最近执行记录 -->
      <van-cell-group inset title="最近执行记录">
        <van-cell 
          v-for="log in recentExecutions" 
          :key="log.id"
          :title="log.ruleName"
          :label="formatDateTime(log.startTime)"
          @click="viewExecutionDetail(log)"
        >
          <template #extra>
            <van-tag :type="getExecutionStatusType(log.executionStatus)" size="small">
              {{ log.executionStatusText }}
            </van-tag>
          </template>
        </van-cell>
        
        <van-cell 
          v-if="recentExecutions.length === 0"
          title="暂无执行记录" 
          center
        />
        
        <van-cell 
          title="查看更多" 
          is-link 
          @click="navigateTo('/datacontrol/execution')"
          center
        />
      </van-cell-group>

      <!-- 快速操作 -->
      <van-cell-group inset title="快速操作" style="margin-top: 12px;">
        <van-cell>
          <template #title>
            <div class="quick-actions">
              <van-button 
                type="primary" 
                size="small" 
                @click="quickAutoControl"
                :loading="autoControlLoading"
              >
                快速自动检控
              </van-button>
              <van-button 
                type="success" 
                size="small" 
                @click="navigateTo('/datacontrol/rules/create')"
              >
                新建规则
              </van-button>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>


<style scoped>
.content {
  padding: 16px;
}

.overview-card {
  margin-bottom: 16px;
}

.overview-info {
  text-align: center;
  padding: 8px 0;
}

.overview-title {
  font-size: 18px;
  font-weight: 600;
  color: #1989fa;
  margin-bottom: 4px;
}

.overview-desc {
  font-size: 14px;
  color: #969799;
  line-height: 1.4;
}

.quick-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.van-cell-group {
  margin-bottom: 12px;
}

.van-cell-group--inset {
  margin: 12px 16px;
}
</style>
